<?php
namespace app\common\repositories\system;
use app\common\repositories\BaseRepository;
use app\common\dao\system\SystemConfigValueDao as dao;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * @mixin dao
 */
class SystemConfigValueRepository extends BaseRepository
{
    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }

    public function more(array $keys, $type): array
    {
        $config = $this->dao->fields($keys, $type);
        foreach ($keys as $key) {
            if (!isset($config[$key])) $config[$key] = '';
        }
        return $config;
    }


    public function get(string $key, $type)
    {
        $value = $this->dao->value($key, $type);
        return $value ?? '';
    }


    public function save(int $cid, array $formData, string $type)
    {
        $keys = array_keys($formData);
        $keys = app()->make(SystemConfigRepository::class)->intersectionKey($cid, $keys);
        if (!count($keys)) return;
        foreach ($keys as $key => $info) {
            if (!isset($formData[$key]))
                unset($formData[$key]);
            else {
                if ($info['config_type'] == 'number') {
                    if ($formData[$key] === '' || $formData[$key] < 0)
                        throw new ValidateException($info['config_name'] . '不能小于0');
                    $formData[$key] = floatval($formData[$key]);
                }
            }
        }
        $this->setFormData($formData, $type);
    }

    public function setFormData(array $formData, string $type)
    {
        Db::transaction(function () use ($type, $formData) {
            foreach ($formData as $key => $value) {
                if ($this->dao->mExists($key, $type))
                    $this->dao->mUpdate($type, $key, ['value' => $value]);
                else
                    $this->dao->create([
                        'type' => $type,
                        'value' => $value,
                        'config_key' => $key
                    ]);
            }
        });
    }
}